package com.nuanshui.heatedloan.msgcenter.service.smspush;

import com.alibaba.fastjson.JSON;
import com.nuanshui.framework.lang.SysStringUtils;
import com.nuanshui.framework.utils.LogUtil;
import com.nuanshui.heatedloan.baseservice.form.StatisticsForm;
import com.nuanshui.heatedloan.constant.RabbitMqQueue;
import com.nuanshui.heatedloan.middleware.rabbitmq.RabbitmqMessageSender;
import com.nuanshui.heatedloan.msgcenter.facade.smspush.SmsPushService;
import com.nuanshui.heatedloan.msgcenter.model.SmsMsg;
import com.nuanshui.heatedloan.msgcenter.model.SmsResultRecord;
import com.nuanshui.heatedloan.msgcenter.model.SmsTemplate;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.context.Context;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;

@Service
public class MandaoSmsPushServiceImpl implements SmsPushService,InitializingBean {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${mandao.sms.notification.sn}")
    private String notificationSn;
    @Value("${mandao.sms.notification.pwd}")
    private String notificationPwd;

    @Value("${mandao.sms.vericode.sn}")
    private String vericodeSn;
    @Value("${mandao.sms.vericode.pwd}")
    private String vericodePwd;

    @Autowired
    private RabbitmqMessageSender rabbitmqMessageSender;

    @Autowired
    private SmsTemplateService smsTemplateService;

    public boolean sendMsg(SmsMsg msg)
    {
        MandaoSmsMsg mandaoSmsMsg=new MandaoSmsMsg();
        BeanUtils.copyProperties(msg,mandaoSmsMsg);

        if(msg.getBizType()==SmsMsg.TYPE_NOTIFICATION)
        {
            mandaoSmsMsg.setSn(notificationSn);
            mandaoSmsMsg.setPwd(notificationPwd);
        }
        else if(msg.getBizType()==SmsMsg.TYPE_VERICODE)
        {
            mandaoSmsMsg.setSn(vericodeSn);
            mandaoSmsMsg.setPwd(vericodePwd);
        }
        return sendMsg(mandaoSmsMsg);
    }

    public boolean sendMsg(MandaoSmsMsg msg) {

        boolean bFlag=false;
        try {

            SmsTemplate smsTemplate=smsTemplateService.getTemplate(msg.getTempCode());

            if(smsTemplate!=null && SysStringUtils.isNotEmpty(smsTemplate.getDesc()))
            {
                MandaoSmsService smsService = new MandaoSmsService(notificationSn, notificationPwd);
                Context context = new VelocityContext(msg.getParams());
                StringWriter sw = new StringWriter();
                try {
                    Velocity.evaluate(context, sw, "velocity", smsTemplate.getDesc());
                } catch (Exception e) {

                    e.printStackTrace();
                }
                String signName="【"+msg.getSignName()+"】";
                String content=sw.toString()+signName;
                content= URLEncoder.encode(content, "utf8");
                //String content=sw.toString()+"【"+"寻宝之旅"+"】";
                String result = smsService.sendNuanshuiSms(msg.getMobile(), content);

                bFlag=true;
                statisticRecord(msg.getMobile(),content,result);
                LogUtil.info(logger,String.format("sendMsg:%s %s",msg.getMobile(),result));
            } else
            {

            }
        } catch (UnsupportedEncodingException e) {

            e.printStackTrace();
        }
        return bFlag;
    }

    private void statisticRecord(String mobile,String content,String result)
    {
        SmsResultRecord resultRecord=new SmsResultRecord();
        resultRecord.setMobile(mobile);
        resultRecord.setContent(content);
        resultRecord.setResult(result);
        resultRecord.setCreatedAt(new Date());

        StatisticsForm form=StatisticsForm.create(resultRecord);
        rabbitmqMessageSender.send(RabbitMqQueue.RABBIT_MQ_STATISTICS,form);
    }

    @Override
    public void afterPropertiesSet() throws Exception {

    }
}
